package com.ming.demo.web.impl;

import com.ming.demo.bean.Result;
import com.ming.demo.common.utils.OssUtils;
import com.ming.demo.service.FileService;
import com.ming.demo.web.UploadController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/upload")
public class UploadControllerImpl implements UploadController {
    @Autowired
    private FileService fileService;

    @Autowired
    private OssUtils ossUtils;

    @Override
    @PostMapping("/upload")
    public Result upload(@RequestParam("file")MultipartFile file, @RequestParam("name") String name, @RequestParam("infoPeople_id")String infoPeople_id) {
            System.out.println(name);
            String fileName = file.getOriginalFilename();
            String filePath = "/tmp/";
            Result<String> result =  new Result<String>();
            File dest = new File(filePath + fileName);
            try{
                file.transferTo(dest);
                if(ossUtils.upload(dest, name, infoPeople_id)){
                    result.setData("success");
                    result.setCode("200");
                    return result;
                }else{
                    result.setCode("500");
                    result.setCode("error");
                    return result;
                }
            }catch (IOException e){
                result.setCode("500");
                result.setCode("error");
                return result;
            }
    }
}
